package com.tj.shopping.web.controller;

import com.tj.shopping.entity.Admin;
import com.tj.shopping.entity.Goods;
import com.tj.shopping.service.IGoodsService;
import com.tj.shopping.service.impl.GoodsServiceImpl;
import com.tj.shopping.util.FileUploadUtil;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/goods")
public class GoodsController extends BaseController {
    private IGoodsService service = new GoodsServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        if (ServletFileUpload.isMultipartContent(req)){
            doAdd(req, resp);
        }else{
            String op = req.getParameter("op");
            if ("findall".equals(op)) {
                doFindall(req, resp);
            } else {
                resp.getWriter().print("no such Method....");
            }
        }
    }



    private void doFindall(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        Map<String,Object> m = service.findall();
        printToJson(resp,m);//响应给页面的是m

    }

    private void doAdd(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        Goods goods = FileUploadUtil.uploadFile(req,Goods.class);
        int result = service.add(goods);
        printToJson(resp,result);
    }
}
